//图片上传
$(function () {
    $("#portrait").wrap("<form id='upload_portrait' action='/customer/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#portrait").change(function () {
        var index = layer.load(2, {
            shade: [0.5,'#fff'] //0.1透明度的白色背景
        });
        $("#upload_portrait").ajaxSubmit({
            dataType: 'json',
            beforeSend: function () {
            },
            uploadProgress: function (event, position, total, percentComplete) {
            },
            success: function (data) {
                if (data.code === 200) {
                    var result = data.result;
                    var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + result.pic;
                    $('.portrait_show').html("<div class='swiper-slide'><img  height='150px' id='portrait_show' src=" + img + "></div>")

                } else {
                    layer.open({
                        content: data.message,
                        btn: ['确认'],
                        shadeClose: false,
                    });
                }
                layer.close(index);
            },
            error: function (xhr) {
                btn_portrait.html("上传失败");
                bar.width('0');
                files_portrait.html(xhr.responseText);
                layer.close(index);
            }
        });
    });
    // 上传凭证
    $("#voucher").wrap("<form id='upload_voucher' action='/customer/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#voucher").change(function () {
        var index = layer.load(2, {
            shade: [0.5,'#fff'] //0.1透明度的白色背景
        });
        $("#upload_voucher").ajaxSubmit({
            dataType: 'json',
            beforeSend: function () {
            },
            uploadProgress: function (event, position, total, percentComplete) {
            },
            success: function (data) {
                if (data.code === 200) {
                    var result = data.result;
                    var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + result.pic;
                    $('.voucher_show').html("<div class='swiper-slide'><img  height='150px' id='voucher_show' src=" + img + "></div>")

                } else {
                    layer.open({
                        content: data.message,
                        btn: ['确认'],
                        shadeClose: false,
                    });
                    return false;
                }
                layer.close(index);
            },
            error: function (xhr) {
                btn_voucher.html("上传失败");
                bar.width('0');
                files_voucher.html(xhr.responseText);
            }
        });
    });
});
// -----------上传图片开始--------------
var panel = ".banner_modify_panel ";
$(document).ready(function () {
    if (product_image_list) {
        var banners = new Array();
        var fnSort = function (a, b) {
            if (a.sort != undefined && b.sort != undefined) {
                return a.sort - b.sort;
            }
        }
        for (var i in product_image_list) {
            banners[i] = product_image_list[i];
        }
        var sort_banners = banners.sort(fnSort),
            rows = sort_banners,
            row = {},
            max_idx = 0,
            i = 0,
            idx = 0;
        //加载图片
        for (var i in rows) {
            row = rows[i];
            idx = row.sort;
            //console.log(row);
            if (idx > max_idx) {
                max_idx = idx;
            }
            var jq_img_li = AddImage(idx, row.img_url, 0);
            jq_img_li.removeClass("hidden");
        }
    }

    max_idx = 0;
    //添加图片的点击事件
    idx = max_idx + 1;
    $(document).on('click', $(panel + " .goods_image .add"), function(){
        AddImage(idx, "", "");
        idx++;
    });
    //拖动
    var ele_parent = panel + ".goods_image ";
    $(ele_parent).dragsort({
        //itemSelector: ".draglist",
        dragSelector: ".real_images",
        dragBetween: true,
        dragEnd: function () {
            return true;
        },
        dragSelectorExclude: ".input_file"
    });
    $(panel + ".panel_reset").bind("click", function () {
        location.reload();
    });
});

AddImage = function (idx, val, default_status) {
    var ele_parent = $(panel).find(".goods_image"),
        ele_li = ele_parent.find("li:last"),
        new_ele = '<li class="real_images hidden draglist" idx='+idx+' draggable="true" style="cursor:move" >'
    var image_last = panel + ".goods_image " + ".real_images:last ";
    if ($(image_last).hasClass('hidden')) {
        return true;
    }
    style =  'style="color:black"';
    if(default_status){
        var style = 'style="color:#88CE20"';
    }
    new_ele += '<a draggable="false" ' + ' target="_blank" >'
        + '<img data-action="zoom" draggable="false" src="' + val + '" alt="" name="images_preview">'
        + '</a>'
        + '<input type="text" class="hidden default_input" name="default[' + idx + ']" value="' + default_status + '">'
        + '<input type="text" class="hidden" name="images[' + idx + ']" value="' + val + '">';
    new_ele += '<p class="main_img"><span style="width: 100%" class="delete">删除</span></p></li>';
    new_jq_ele = $(new_ele);
    new_jq_ele.find(".delete").on("mousedown", function () {//删除图片事件
        var temp = confirm('是否确定删除');
        if (temp == false) {
            return false;
        }
        $(this).closest("li").remove();
    });
    new_jq_ele.find(".default").on("mousedown", function () {//设置默认图片
        $(".main_img .default").removeAttr('style');
        $(this).attr('style','color:#88CE20');
        $("input[name^=default]").val(0);
        $("input[name='default["+idx+"]']").val(1);
    });
    new_jq_ele.insertBefore($(ele_li));
    return new_jq_ele;
}
//图片上传
$(function () {
    $('input[name=imagefield]').click(function(){
        var image_list = [];
        var n = 0;
        $("input[name^=images]").each(function(i){
            if(this.value !=''){
                image_list[i] = this.value;
                n++;
            }
        });
        if (n > 4) {
            layer.alert('打款凭证最多上传五张');return false;
        }
        $('#fileupload').click();
    });
    var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        slidesPerView: 5,
        paginationClickable: true,
        spaceBetween: 10,
        freeMode: true
    });
    var bar = $('.bar');
    var percent = $('.percent');
    var progress = $(".progress");
    var files = $(".files");
    var files_details = $(".files_details");
    var btn = $(".btn_");
    var btn_details = $(".btn_details");
    $("#fileupload").wrap("<form id='myupload' action='/image/upload-image' method='post' enctype='multipart/form-data'></form>");
    $("#fileupload").change(function(){
        var ele_parent = panel + ".goods_image ",
            li_last = ele_parent + "li:last ",
            image_last = ele_parent + ".real_images:last ";
        var index = layer.msg('上传中...', {icon: 16,shade: [0.5, '#f5f5f5'],scrollbar: false,offset: '0px', time:1000000}) ;
        $("#myupload").ajaxSubmit({
            data:{'type':'product_img'},
            dataType:  'json',
            beforeSend: function() {
            },
            uploadProgress: function(event, position, total, percentComplete) {
            },
            success: function(res) {
                var data = res.result;
                layer.close(index);
                $(image_last).removeClass('hidden');
                var img = "http://xianyongta.oss-cn-shanghai.aliyuncs.com/files/" + data.pic;
                $(image_last + "img").attr("src", img);
                $(image_last + "input[name^=images]").val('files/'+data.pic);
            },
            error:function(xhr){
                layer.close(index);
                btn.html("上传失败");
                bar.width('0');
                files.html(xhr.responseText);
            }
        });
    });
});
/**
 * 取对象个数
 * @param o
 * @returns {*}
 */
function count(o){
    var t = typeof o;
    if(t == 'string'){
        return o.length;
    }else if(t == 'object'){
        var n = 0;
        for(var i in o){
            n++;
        }
        return n;
    }
    return false;
}
// -----------上传图片结束--------------
/**
 * 检测登录账号是否可用
 */
function checkLoginAccount() {
    var login_account = $("#login_account").val(); // 判断登录账号
    var index = layer.load(2, {
        shade: [0.5, '#fff'] //0.1透明度的白色背景
    });
    $.ajax({
        type: 'post',
        url: '/customer/check-login-account',
        data: {login_account: login_account},
        dateType: 'json',
        success: function (response) {
            if (response.code === 200) {
                layer.alert(response.message);
            } else {
                layer.alert(response.message);
            }
            layer.close(index);
        }
    });
}

/**
 * 重置密码
 */
function restPassword() {
    var customer_id = $("#customer_id").val();
    var index = layer.load(2, {
        shade: [0.5, '#fff'] //0.1透明度的白色背景
    });
    $.ajax({
        type: 'post',
        url: '/customer/reset-password',
        data: {customer_id: customer_id},
        dateType: 'json',
        success: function (response) {
            if (response.code === 200) {
                layer.alert(response.message);
                window.location.reload();
            } else {
                layer.alert(response.message);
            }
            layer.close(index);
        }
    });
}
function save() {
    var name = $("#name").val(); // 客户姓名
    var login_account = $("#login_account").val(); // 登录账号
    var password = $("#password").val(); // 登录密码
    var telephone = $("#telephone").val(); // 联系电话
    var province_id = $("#province").val(); // 省id
    var city_id = $("#city").val(); // 市id
    var area_id = $("#area").val(); // 区id
    var address = $("#address").val(); //  详细地址
    var wechat_account = $("#wechat_account").val(); //微信昵称
    var identity_card_number = $("#identity_card_number").val(); // 身份证号
    var status = $("#customer_status").val();
    var portrait = $('#portrait_show').attr('src'); // 客户头像
    var admin_remark = $("#admin_remark").val(); //管理员备注
    $.ajax({
        type: 'post',
        url: '/customer/insert',
        data: {
            'name': name,
            'login_account': login_account,
            'password': password,
            'telephone': telephone,
            'province_id': province_id,
            'city_id': city_id,
            'area_id': area_id,
            'address': address,
            'wechat_account': wechat_account,
            'identity_card_number': identity_card_number,
            'status': status,
            'portrait': portrait,
            'admin_remark':admin_remark
        },
        beforeSend: function () {
            var index = layer.msg('客户添加中...', {
                icon: 16,
                shade: [0.5, '#f5f5f5'],
                scrollbar: false,
                offset: '0px',
                time: 1000000
            });
        },
        dataType: 'json',
        success: function (response) {
            if (response.code == 200) {
                layer.alert(response.message, function () {
                    window.location.href = '/customer/list';
                    return false;
                });
            } else {
                layer.alert(response.message, function () {
                    layer.closeAll();
                });
                return false;
            }
        }
    });
}

function update() {
    var customer_id = $("#customer_id").val(); // 客户id
    var name = $("#customer_name_input").val(); // 客户姓名
    var login_account = $("#login_account").val(); // 登录账号
    var password = $("#password").val(); // 登录密码
    if(password==''){
        layer.alert('请输入密码！');return false;
    }
    var telephone = $("#telephone").val(); // 联系电话
    var province_id = $("#province").val(); // 省id
    var city_id = $("#city").val(); // 市id
    var area_id = $("#area").val(); // 区id
    var address = $("#address").val(); //  详细地址
    var wechat_account = $("#wechat_account").val(); //微信昵称
    var identity_card_number = $("#identity_card_number").val(); // 身份证号
    var rank_id = $("#rank").val(); //等级id
    var parent_customer_id = $("#search_customer_id").val(); // 上级
    var status = $("#customer_status").val();
    var admin_remark = $("#admin_remark").val();
// ------------支付信息--------------//
    var customer_payment_id = $("#customer_payment_id").val(); // 客户支付id
    var customer_payment_method = $("#customer_payment_method").val(); // 打款方式
    var payment_amount = $("#payment_amount").val(); // 打款金额
    var bank_name = $("#bank_name").val(); // 开户银行
    var bank_account = $("#bank_account").val(); // 银行户名
    var bank_number = $("#bank_number").val(); // 银行户名
    var portrait = $('#portrait_show').attr('src'); // 客户头像
    var alipay_account = $("#alipay_account").val(); // 支付宝账号
    var remark = $("#remark").val();
    //商品图片数组
    var image_list = [];

    $("input[name^=images]").each(function(i){
        if(this.value !=''){
            image_list[i] = this.value;
        }
    });
    if (count(image_list) > 5) {
        layer.alert('产品图片最多上传五张');return false;
    }
    $.ajax({
        type: 'post',
        url: '/customer/update',
        data: {
            'customer_id':customer_id,
            'name': name,
            'login_account': login_account,
            'password': password,
            'telephone': telephone,
            'province_id': province_id,
            'city_id': city_id,
            'area_id': area_id,
            'address': address,
            'wechat_account': wechat_account,
            'identity_card_number': identity_card_number,
            'rank_id': rank_id,
            'parent_customer_id': parent_customer_id,
            'status': status,
            'customer_payment_id': customer_payment_id,
            'customer_payment_method': customer_payment_method,
            'payment_amount': payment_amount,
            'bank_name': bank_name,
            'bank_account': bank_account,
            'bank_number':bank_number,
            'portrait': portrait,
            'alipay_account': alipay_account,
            'voucher': image_list,
            'remark':remark,
            'admin_remark':admin_remark
        },
        beforeSend: function () {
            var index = layer.msg('客户更新中...', {
                icon: 16,
                shade: [0.5, '#f5f5f5'],
                scrollbar: false,
                offset: '0px',
                time: 1000000
            });
        },
        dataType: 'json',
        success: function (response) {
            if (response.code == 200) {
                layer.alert(response.message, function () {
                    // window.location.href = '/customer/list';
                    window.history.back();
                    return false;
                });
            } else {
                $(".save_product").attr("disabled", false);
                layer.alert(response.message, function () {
                    layer.closeAll();
                    window.location.reload();
                    return false;
                });

            }
        }
    });
}
function updateStatus(e) {
    var customer_id = $("#customer_id").val(); // 客户id
    var action = $(e).attr('action');
    $.ajax({
        type: 'post',
        url: '/customer/update-status',
        data: {
            'customer_id':customer_id,
            'action': action
        },
        beforeSend: function () {
            var index = layer.msg('更新状态中...', {
                icon: 16,
                shade: [0.5, '#f5f5f5'],
                scrollbar: false,
                offset: '0px',
                time: 1000000
            });
        },
        dataType: 'json',
        success: function (response) {
            if (response.code == 200) {
                layer.alert(response.message, function () {
                    window.location.reload();
                    return false;
                });
            } else {
                layer.alert(response.message, function () {
                    layer.closeAll();
                });
                window.location.reload();
            }
        }
    });
}